package controllers;

import java.util.Date;

import models.User;
import play.data.validation.Required;
import play.libs.Crypto;
import play.mvc.Controller;
import play.mvc.Http;

public class UserManager extends Controller {

/*********************** User management **************************/
	
	public static void index() {
		Http.Cookie remember = request.cookies.get("rememberme");
		if(remember != null) {
			int firstIndex = remember.value.indexOf("-");
			int lastIndex = remember.value.lastIndexOf("-");
			if (lastIndex > firstIndex) {
				String sign = remember.value.substring(0, firstIndex);
				String restOfCookie = remember.value.substring(firstIndex + 1);
				String username = remember.value.substring(firstIndex + 1, lastIndex);
				String time = remember.value.substring(lastIndex + 1);
				Date expirationDate = new Date(Long.parseLong(time)); // surround with try/catch?
				Date now = new Date();
				try {
					if (expirationDate == null || expirationDate.before(now)) {
						MySecure.logout();

					}
					if(Crypto.sign(restOfCookie).equals(sign)) {
						session.put("username", username);
						Application.home();
					}
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		render();
	}    
	
	public static void logout() throws Throwable {
		MySecure.logout();
	}
	public static void register() {
		render();
	}

	public static void newUser(@Required String firstName, @Required String lastName, @Required String email,
			@Required String userName, @Required String password, @Required String repeatPassword, String gender, @Required Date date, 
			String phoneNumber, @Required String town) {

		validation.match(gender, "male||female");
		//validation.minSize(password.length(), 7);
		validation.equals("repeatPassword", repeatPassword, "password", password);


		if(validation.hasErrors()) {
			flash.error("Please fill all the fields.");
			params.flash();
			validation.keep();
			register();
		}
		User user = new User(firstName, lastName, email, userName, password, gender, date,
				phoneNumber, town); 
		user.save();


		try {
			login(userName, password, false);
			Application.home();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void privacyNotice() {
		render();
	}

	public static void condOfUse() {
		render();
	}

	public static void login(@Required String username, String password, boolean remember) throws Throwable {
		MySecure.authenticate(username, password, remember, 5);
	}
	
}
